package com.ucs.restlet.firstres;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.spi.ErrorCode;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ItemsResource extends BaseResource{
	/**
	 * Handle POST requests: create a new item
	 */
	
	@Post
	public Representation acceptItem(Representation entity){
		try {
			InputRepresentation ir = (InputRepresentation)entity;
			String text = ir.getText();
			System.out.println("ItemsResource:acceptItem:"+text);
			Item newItem = (Item)XStremUtil.toJava(text);
			Representation result = null;
			if (!getItems().containsKey(newItem.getName()) && getItems().putIfAbsent(newItem.getName(), newItem) == null) {   
	            // Set the response's status and entity   
	            setStatus(Status.SUCCESS_CREATED);   
	            result = new StringRepresentation("Item created",MediaType.TEXT_PLAIN);   
	            // Indicates where is located the new resource.   
	            result.setIdentifier(getRequest().getResourceRef().getIdentifier() + "/" + newItem.getName());   
	        } else { // Item is already registered.   
	            setStatus(Status.CLIENT_ERROR_NOT_FOUND);   
	            result = generateErrorRepresentation("Item " + newItem.getName() + " already exists.", "1");   
	        }   		
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**  
     * Generate an XML representation of an error response.  
     *   
     * @param errorMessage  
     *            the error message.  
     * @param errorCode  
     *            the error code.  
     */  
    private Representation generateErrorRepresentation(String errorMessage,   
            String errorCode) { 
    	ErrorResp ec = new ErrorResp(errorCode, errorMessage);
    	try {
        	return new StringRepresentation(XStremUtil.toXML(ec));			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }   
    
    @Get("xml")
    public Representation toXml(){
    	try {
    		List<Item> l = new ArrayList<Item>(getItems().values().size());
    		for (Item item : getItems().values()) {
    			l.add(item);
			}
			return new StringRepresentation(XStremUtil.toXML(l));
		} catch (Exception e) {
			e.printStackTrace();   
			return null;
		}
    	
    }
}
